/*
 * @Author: jiu yin
 * @Date: 2023-06-01 11:43:29
 * @LastEditTime: 2024-06-04 11:53:49
 * @LastEditors: jiu yin zhen jing
 * @FilePath: \studio-web-admin\src\router\auth\index.tsx
 * jiu
 */
import { useState, useEffect } from "react";
import "./index.scss";
import { useLocation, useNavigate, Navigate } from "react-router-dom";
import { getToken } from "@/utils/auth";
import routeArr from "@/router/routerArr";
import { deepClone, dispose } from "@/utils";
import { useSelector, useDispatch } from "react-redux";
import { path_home } from "@/utils/auth";

function Auth(props: any) {
   let location = useLocation();
   let navigate = useNavigate();
   const userInfo = useSelector((state: any) => state.user.userInfo);

   if (location.pathname === "/login") return props.children;
   if (location.pathname === "/register_union") return props.children;

   //首页暂时没有 跳转到有权限的 第一个路由

   let routerArrDeep: [] = deepClone(routeArr);
   let items = dispose(routerArrDeep);

   let { roleList } = userInfo;

   let token = getToken();
   if (!token) return <Navigate to="/login" />;
   if (roleList.length === 0) return <Navigate to="/404" />;

   // if (location.pathname === "/") {
   //    //path_home() 要加载后才执行，  但之前login你或者404 跳转会记录
   //    let path_home_str = window.sessionStorage.getItem("path_home") || "/login";
   //    return <Navigate to="/login" />;
   // }

   items.forEach((item: any) => {
      if (item.children && item.children.length > 0) {
         item.children.forEach((i: any) => {
            if (i.path === location.pathname) {
               if (i.meta?.key == undefined) return props.children;
               if (roleList.includes(i.meta.key)) {
                  return props.children;
               } else {
                  navigate("/404");
                  return <Navigate to="/404" />;
               }
            }
         });
      }
   });

   return props.children;
}

export default Auth;
